package com.hupu.jrs.ui.post

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import com.afollestad.materialdialogs.MaterialDialog
import com.facebook.drawee.view.SimpleDraweeView
import com.hupu.jrs.R
import com.hupu.jrs.bean.BaseError
import com.hupu.jrs.bean.Exam
import com.hupu.jrs.ui.BaseSwipeBackActivity
import com.hupu.jrs.ui.browser.BrowserActivity
import com.hupu.jrs.ui.gallery.GalleryActivity
import java.io.File
import java.util.ArrayList
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife
import rx.Observable
import rx.functions.Action1

/**
 * Created by sll on 2016/3/9.
 */
class PostActivity : BaseSwipeBackActivity(), PostContract.View {

    @BindView(R.id.toolbar)
    internal var toolbar: Toolbar? = null
    @BindView(R.id.etSubject)
    internal var etSubject: EditText? = null
    @BindView(R.id.etContent)
    internal var etContent: EditText? = null
    @BindView(R.id.llPics)
    internal var llPics: LinearLayout? = null
    @BindView(R.id.scrollView)
    internal var scrollView: HorizontalScrollView? = null

    private val selectImages = ArrayList<String>()
    private var mDialog: MaterialDialog? = null

    private var title: String? = null
    private var type: Int = 0
    private var fid: String? = null
    private var tid: String? = null
    private var pid: String? = null

    @Inject
    internal var mPresenter: PostPresenter? = null

    // 暂时只支持删除，不支持预览
    internal var onPictureClickListener: View.OnClickListener = View.OnClickListener { v ->
        val path = v.tag.toString()

        AlertDialogWrapper.Builder(this@PostActivity).setMessage("确定删除图片")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which ->
                    selectImages.remove(path)
                    for (i in 0 until llPics!!.childCount) {
                        val view = llPics!!.getChildAt(i)

                        if (view.tag.toString() == path) {
                            llPics!!.removeView(view)
                            break
                        }
                    }

                    if (selectImages.isEmpty()) {
                        scrollView!!.visibility = View.GONE
                    }
                })
                .show()
    }

    override fun initContentView(): Int {
        return R.layout.activity_post
    }

    override fun initInjector() {
        DaggerPostComponent.builder()
                .applicationComponent(applicationComponent)
                .activityModule(activityModule)
                .build()
                .inject(this)
    }

    override fun initUiAndListener() {
        ButterKnife.bind(this)
        mPresenter!!.attachView(this)
        initToolBar(toolbar)
        initBundle()
        initPostType()
        initDialog()
    }

    override fun onResume() {
        super.onResume()
        mPresenter!!.checkPermission(type, fid, tid)
    }

    private fun initDialog() {
        mDialog = MaterialDialog.Builder(this).title("提示").content("正在发送").progress(true, 0).build()
    }

    private fun initBundle() {
        val intent = intent
        type = intent.getIntExtra("type", Constants.TYPE_COMMENT)
        title = intent.getStringExtra("title")
        fid = intent.getStringExtra("fid")
        tid = intent.getStringExtra("tid")
        pid = intent.getStringExtra("pid")
    }

    private fun initPostType() {
        when (type) {
            Constants.TYPE_COMMENT -> {
                setTitle("评论")
                etSubject!!.isFocusable = false
                etSubject!!.isFocusableInTouchMode = false
                etSubject!!.setText("Reply:" + title!!)
                etContent!!.hint = "请输入评论内容"
            }
            Constants.TYPE_REPLY -> {
                setTitle("评论")
                etSubject!!.isFocusable = false
                etSubject!!.isFocusableInTouchMode = false
                etSubject!!.setText("Reply:" + title!!)
                etContent!!.hint = "请输入评论内容"
            }
            Constants.TYPE_AT -> {
                setTitle("评论")
                etSubject!!.isFocusable = false
                etSubject!!.isFocusableInTouchMode = false
                etSubject!!.setText("Reply:" + title!!)
                etContent!!.hint = "请输入评论内容"
            }
            Constants.TYPE_FEEDBACK -> {
                setTitle("反馈")
                etSubject!!.isFocusable = false
                etSubject!!.isFocusableInTouchMode = false
                etSubject!!.setText("Feedback: TLint For Android")
                etContent!!.hint = "请输入反馈内容"
            }
            Constants.TYPE_QUOTE -> {
                setTitle("引用")
                etSubject!!.isFocusable = false
                etSubject!!.isFocusableInTouchMode = false
                etSubject!!.setText("Quote:" + title!!)
                etContent!!.hint = "请输入评论内容"
            }
            else -> setTitle("发新帖")
        }
    }

    override fun isApplyStatusBarTranslucency(): Boolean {
        return true
    }

    override fun isApplyStatusBarColor(): Boolean {
        return true
    }

    fun renderError(error: BaseError?) {
        if (error != null) {
            println(error.text)
            MaterialDialog.Builder(this).title("温馨提示")
                    .content(error.text!!)
                    .cancelable(false)
                    .positiveText("确定")
                    .callback(object : MaterialDialog.ButtonCallback() {
                        override fun onPositive(dialog: MaterialDialog?) {
                            finish()
                        }
                    })
                    .show()
        }
    }

    fun renderExam(exam: Exam?) {
        if (exam != null) {
            MaterialDialog.Builder(this).title("温馨提示")
                    .content(exam.title!!)
                    .cancelable(false)
                    .positiveText("开始答题")
                    .negativeText("放弃答题")
                    .callback(object : MaterialDialog.ButtonCallback() {
                        override fun onPositive(dialog: MaterialDialog?) {
                            BrowserActivity.startActivity(this@PostActivity, exam.url, false)
                        }

                        override fun onNegative(dialog: MaterialDialog?) {
                            finish()
                        }
                    })
                    .show()
        }
    }

    override fun showLoading() {
        if (!mDialog!!.isShowing && !isFinishing) {
            mDialog!!.show()
        }
    }

    override fun hideLoading() {
        if (mDialog!!.isShowing && !isFinishing) {
            mDialog!!.dismiss()
        }
    }

    override fun postSuccess() {
        Observable.timer(2, TimeUnit.SECONDS).subscribe { finish() }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_post, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == R.id.action_send) {
            send()
        } else if (id == R.id.action_camera) {
            GalleryActivity.startActivity(this, selectImages)
        } else if (id == android.R.id.home) {
            finish()
        }
        return true
    }

    private fun send() {
        mPresenter!!.parse(selectImages)
        val content = etContent!!.text.toString()
        if (type == Constants.TYPE_POST) {
            val title = etSubject!!.text.toString()
            mPresenter!!.post(fid, content, title)
        } else {
            mPresenter!!.comment(tid, fid, pid, content)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GalleryActivity.REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
            // 获取返回的图片列表
            val path = data.getStringArrayListExtra(GalleryActivity.EXTRA_RESULT)
            // 处理你自己的逻辑 ....
            selectImages.clear()
            selectImages.addAll(path)
            updatePicsUI()
        }
    }

    private fun updatePicsUI() {
        if (selectImages.isEmpty()) {
            scrollView!!.visibility = View.GONE
            llPics!!.visibility = View.GONE
        } else {
            scrollView!!.visibility = View.VISIBLE
            llPics!!.visibility = View.VISIBLE
            llPics!!.removeAllViews()
            for (path in selectImages) {
                val itemView = View.inflate(this, R.layout.item_post_pic, null)
                val ivPic = itemView.findViewById<View>(R.id.ivPic) as SimpleDraweeView
                itemView.tag = path
                itemView.setOnClickListener(onPictureClickListener)
                ivPic.setImageURI(Uri.fromFile(File(path)))
                llPics!!.addView(itemView,
                        LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter!!.detachView()
    }

    companion object {

        fun startActivity(mContext: Context, type: Int, fid: String, tid: String, pid: String,
                          title: String) {
            val intent = Intent(mContext, PostActivity::class.java)
            intent.putExtra("type", type)
            intent.putExtra("fid", fid)
            intent.putExtra("tid", tid)
            intent.putExtra("pid", pid)
            intent.putExtra("title", title)
            mContext.startActivity(intent)
        }
    }
}
